<template>
  <div class="publication-view">
    <div class="top">
      <input v-model="form.title" placeholder="输入文章标题" :maxlength="40" />
      <el-popover placement="bottom" width="400" trigger="click" ref="popover">
        <el-form ref="form" :model="form" label-width="80px">
          <div class="publication-title"><span>发表文章</span></div>
          <el-form-item
            label="分类："
            prop="categoryId"
            :rules="[
              { required: true, message: '请选择分类', trigger: 'blur' },
            ]"
          >
            <!-- 转为string-->
            <el-radio-group v-model="form.categoryId" size="mini">
              <el-radio label="1" border>前端</el-radio>
              <el-radio label="2" border>后端</el-radio>
              <el-radio label="3" border>人工智能</el-radio>
              <el-radio label="4" border>阅读</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="标签："
            prop="tagIds"
            :rules="[
              { required: true, message: '请选择标签', trigger: 'blur' },
              {
                type: 'array',
                max: 3,
                message: '最多只能选择3个标签',
                trigger: 'change',
              },
            ]"
          >
            <el-select
              v-model="form.tagIds"
              size="small"
              style="width: 95%"
              filterable
              clearable
              multiple
              placeholder="请选择标签"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="封面：">
            <el-upload
              class="avatar-uploader"
              action="'#'"
              :show-file-list="false"
              :auto-upload="false"
              :on-change="beforeAvatarUpload"
              ref="upload"
            >
              <img v-if="form.coverImg" :src="form.coverImg" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              <svg-icon
                v-if="form.coverImg"
                @click="clearCoverImg"
                style="
                  position: absolute;
                  right: 0;
                  top: 0;
                  width: 20px;
                  height: 20px;
                  background-color: #1e80ff;
                  color: #fff;
                "
                icon-file-name="close"
              ></svg-icon>
            </el-upload>
          </el-form-item>
          <el-form-item
            label="摘要："
            prop="summary"
            :rules="[
              { required: true, message: '请输入摘要', trigger: 'blur' },
              {
                min: 50,
                max: 100,
                message: '摘要长度应为50到100个字符',
                trigger: 'blur',
              },
            ]"
          >
            <el-input
              type="textarea"
              placeholder="请输入摘要"
              v-model="form.summary"
              :autosize="{ minRows: 2, maxRows: 4 }"
              :max-length="100"
            >
            </el-input>
          </el-form-item>
          <el-form-item
            style="border-top: 1px solid #ebeef5; padding-top: 10px"
          >
            <el-button plain style="margin-right: 40px" @click="clear"
              >取消</el-button
            >
            <el-button type="primary" :disabled="isDisabled" @click="publish"
              >发布</el-button
            >
          </el-form-item>
        </el-form>
        <el-button type="primary" slot="reference" @click="publishFormBtn"
          >发 布</el-button
        >
      </el-popover>
    </div>
    <div class="bottom">
      <mavon-editor v-model="form.content" />
    </div>
  </div>
</template>

<script>
import { mavonEditor } from "mavon-editor";
import "mavon-editor/dist/css/index.css";
import markdownToText from "markdown-to-text"; // markdown转文本
import { publishPost, getTagsData, updatePost } from "../../api/publication";
import { getUserId } from "../../utils/auth";
export default {
  components: {
    mavonEditor,
  },
  data() {
    return {
      // 路由接收到的参数
      postId: this.$route.params.postId,
      postData: this.$route.params.postData,
      // 本页表单
      form: {
        postId: "",
        title: "",
        content: "",
        categoryId: "",
        tagIds: [],
        coverImg: "",
        summary: "",
        userId: getUserId(),
      },
      options: [],
      // 是否禁用发布按钮
      isDisabled: false,
    };
  },
  methods: {
    // 清空封面图片
    clearCoverImg(event) {
      event.stopPropagation();
      this.form.coverImg = "";
    },
    publishFormBtn() {
      if (parseInt(this.postId) === 0)
        this.form.summary = markdownToText(this.form.content.slice(0, 100));
      console.log(this.form);
      // 获取标签数据
      getTagsData().then((res) => {
        if (res.data.code === 1) {
          const formattedData = res.data.data.map((item) => ({
            label: item.tag_name,
            value: item.tag_id,
          }));
          this.options = formattedData;
        }
      });
    },
    // 取消
    clear() {
      this.form.categoryId = "";
      this.form.coverImg = "";
      this.form.tagIds = [];
      this.form.summary = "";
      this.$refs.form.resetFields();
      this.$refs.popover && this.$refs.popover.doClose();
    },
    // 发布
    publish() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 表单验证通过后的处理逻辑，例如提交表单
          if (!this.form.title) {
            this.$notify.error({
              title: "错误",
              message: "请输入文章标题",
            });
            return;
          }
          // 将postId转为int
          if (parseInt(this.postId) === 0) {
            // 发布文章
            publishPost(this.form).then((res) => {
              if (res.data.code === 1) {
                this.$refs.popover && this.$refs.popover.doClose();
                this.$router.push("/publication/success");
              } else {
                this.$messages.error("发布失败，网络错误");
              }
            });
          } else {
            // 更新文章
            console.log(this.form);
            updatePost(this.form).then((res) => {
              if (res.data.code === 1) {
                this.$refs.popover && this.$refs.popover.doClose();
                this.$router.push("/publication/success");
              } else {
                this.$messages.error("发布失败，网络错误");
              }
            });
          }
        }
      });
    },
    beforeAvatarUpload(file) {
      const isJPG =
        file.raw.type === "image/jpeg" || file.raw.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 或 PNG 格式!");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
        return false;
      }

      // 使用 file.raw 访问实际的 File 对象，暂时显示在屏幕上面
      const actualFile = file.raw;
      if (actualFile instanceof Blob) {
        // 使用 FileReader 读取文件并生成 base64 URL
        const reader = new FileReader();
        reader.onload = (e) => {
          this.form.coverImg = e.target.result; // 将图片URL存储到imgUrl变量
        };
        reader.readAsDataURL(actualFile); // 将文件读取为Data URL
      } else {
        console.error("The uploaded file is not a valid Blob or File object.");
      }
      return false;
    },
    // 刷新提示
    confirmExit(event) {
      const message = "修改未提交，是否离开？";
      event.returnValue = message; // 兼容某些浏览器
      return message; // 标准的方式来显示消息
    },
  },
  mounted() {
    if (parseInt(this.postId) !== 0) {
      this.form.postId = this.postData.postId;
      this.form.title = this.postData.title;
      this.form.content = this.postData.content;
      this.form.categoryId = this.postData.categoryId.toString();
      this.form.tagIds = this.postData.tagIds;
      this.form.coverImg = this.postData.coverImg;
      this.form.summary = this.postData.summary;
    }
    // 监听刷新事件
    window.addEventListener("beforeunload", this.confirmExit);
  },
  beforeDestroy() {
    window.removeEventListener("beforeunload", this.confirmExit);
  },
};
</script>

<style lang="less" scoped>
@import url("../../assets/ElementUIStyle/el-button.css");
.publication-view {
  height: 100%;
  .top {
    height: 50px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
    padding: 0 20px 0 15px;
    background-color: #ffffff;
    box-shadow: rgba(0, 0, 0, 0.1) 0px 2px 12px 0px;
    input {
      height: 95%;
      width: 700px;
      font-size: 22px;
      border: none;
      color: #1d2129;
      &:focus {
        border: none;
        outline: none;
      }
    }
  }
  .bottom {
    height: calc(100% - 60px);
    .mavon-editor {
      height: 100%;
    }
  }
}
.publication-title {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 10px;
  border-bottom: 1px solid #e5e6eb;
  padding-bottom: 10px;
}
</style>

<style scoped>
::v-deep .el-textarea__inner {
  min-height: 80px !important;
}
::v-deep .el-popover.el-popper {
  padding: 0 !important;
}
/* 文件上传 */
.avatar-uploader {
  margin-top: 12px !important;
}

::v-deep .el-upload .el-upload--text {
  position: relative;
}

::v-deep .el-upload svg {
  display: none !important;
}

::v-deep .el-upload:hover svg {
  display: block !important;
}

::v-deep .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 192px;
  height: 128px;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 192px;
  height: 128px;
  line-height: 200px;
  text-align: center;
}
.avatar {
  width: 192px;
  height: 128px;
  display: block;
}
.el-icon-plus:before {
  display: flex;
  justify-content: center;
  align-items: center;
  widows: 192px;
  height: 128px;
}
/* markdown */
.markdown-body {
  height: 100%;
}
.v-note-wrapper {
  border-radius: 0;
}
::v-deep .el-radio__input {
  display: none !important;
}
.el-radio--mini.is-bordered {
  padding: 5px !important;
  text-align: center !important;
  width: 70px !important;
}
::v-deep .el-radio__label {
  padding: 0 !important;
}
.el-radio-group {
  display: flex;
  flex-wrap: wrap;
}
::v-deep .el-radio {
  margin-right: 0 !important;
}
.el-radio-group {
  margin-top: 8px !important;
}
.el-textarea {
  margin-top: 12px !important;
}
</style>